﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Sgr.AspNetCore.ActionFilters.AuditLogs;
using Sgr.Indentity.Application.Commands;

namespace Sgr.Indentity.Controllers
{
    /// <summary>
    /// 验证码控制器
    /// </summary>
    [Route("api/v1/sgr/verify-code")]
    [ApiController]
    [AllowAnonymous]
    [Produces("application/json")]
    [Tags("VerifyCode")]
    public class VerifyCodeController : ControllerBase
    {
        private readonly IMediator _mediator;

        /// <summary>
        /// 初始化安全校验控制器
        /// </summary>
        /// <param name="mediator">中介者服务</param>
        public VerifyCodeController(IMediator mediator)
        {
            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="commond">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">发送成功</response>
        /// <response code="400">请求参数验证失败</response>
        /// <response code="429">请求过于频繁</response>
        [HttpPost("send")]
        [EnableRateLimiting("RateLimiterPolicy.Sgr.Identity.VerifyCode")]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status429TooManyRequests)]
        [AuditLogActionFilter("发送验证码")]
        public async Task<ActionResult<bool>> SendAsync(
            [FromBody] SendVerificationCodeCommand commond, System.Threading.CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(commond, cancellationToken);

            return !result.IsSuccess ? this.CustomBadRequest(result.Message) : Ok(result.Data);
        }

        /// <summary>
        /// 验证验证码（验证成功后会清除验证码）
        /// </summary>
        /// <param name="command">验证码验证命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>验证结果</returns>
        /// <response code="200">验证成功</response>
        /// <response code="400">验证失败或请求参数验证失败</response>
        /// <response code="429">请求过于频繁</response>
        [HttpPost("verify")]
        [EnableRateLimiting("RateLimiterPolicy.Sgr.Identity.VerifyCode")]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status429TooManyRequests)]
        [AuditLogActionFilter("验证验证码")]
        public async Task<ActionResult<bool>> VerifyAsync(
            [FromBody] VerifyCodeCheckCommand command, System.Threading.CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(command, cancellationToken);
            return !result.IsSuccess ? this.CustomBadRequest(result.Message) : Ok(result.Data);
        }
    }
}